# -*- coding: utf-8 -*-

from tablestore import *

from GKModel.BaseModel import BaseModel


class Advertisement(BaseModel):
    TABLE_NAME = 'Advertisement'

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def query_by_cid(self, cid, next_start_primary_key=None, limit=10):
        inclusive_start_primary_key = [('category_id', cid), ('aid', INF_MIN)] \
            if next_start_primary_key is None \
            else next_start_primary_key
        exclusive_end_primary_key = [('category_id', cid), ('aid', INF_MAX)]
        columns_to_get = []

        def query():
            return self.ots_client.get_range(
                table_name=Advertisement.TABLE_NAME,
                direction=Direction.FORWARD,
                inclusive_start_primary_key=inclusive_start_primary_key,
                exclusive_end_primary_key=exclusive_end_primary_key,
                columns_to_get=columns_to_get,
                limit=limit,
                max_version=1
            )

        try:
            consumed, next_start_primary_key, row_list, next_token = query()
            result = []
            for row in row_list:
                item = dict(row.primary_key)
                for att in row.attribute_columns:
                    item[att[0]] = att[1]
                result.append(item)

            return result, next_start_primary_key
        except OTSServiceError as e:
            raise ValueError(1000021, e.get_error_message())
        except OTSClientError as e:
            raise ValueError(1000021, e.get_error_message())


def new(**kwargs) -> Advertisement:
    return Advertisement(**kwargs)
